import { Controller, Post, Body } from '@nestjs/common';
import { AuthService } from './auth.service';
import { AuthenticationSelector } from './authentication-selector';
import { ApiException } from 'src/common/filter/http-exception/api.exception';
import { ApiErrorCode } from 'src/common/enums/api-error-code.enum';
import { Public } from 'src/modules/auth/public.decorator';
import { validate } from 'class-validator';
import { MobileLoginDto } from './dto/mobile-login.dto';
import { PasswordLoginDto } from './dto/password-login.dto';

@Controller('auth')
export class AuthController {
  constructor(
    private readonly authService: AuthService,
    private readonly authSelector: AuthenticationSelector,
  ) { }

  @Post('login/mobile')
  @Public()
  async loginMobile(@Body() loginDto: MobileLoginDto) {
    const errors = await validate(loginDto);

    if (errors.length > 0) {
      throw new ApiException('Validation failed', ApiErrorCode.USER_ID_INVALID);
    }

    const authenticationStrategy = this.authSelector.selectStrategy('mobile');
    const user = await authenticationStrategy.authenticate(loginDto);

    return this.getToken(user); // 返回令牌给客户端
  }

  @Post('login/password')
  @Public()
  async loginPassword(@Body() loginDto: PasswordLoginDto) {
    const errors = await validate(loginDto);

    if (errors.length > 0) {
      throw new ApiException('Validation failed', ApiErrorCode.USER_ID_INVALID);
    }

    const authenticationStrategy = this.authSelector.selectStrategy('password');
    const user = await authenticationStrategy.authenticate(loginDto);

    return this.getToken(user); // 返回令牌给客户端
  }

  getToken(user: any) {
    if (user) {
      // 生成JWT令牌
      const payload = { sub: user.id, username: user.username }; // 自定义令牌的负载
      const token = this.authService.generateJwtToken(payload);

      // 返回令牌给客户端
      return { access_token: token };
    } else {
      // 身份验证失败
      throw new ApiException(
        'Authentication failed',
        ApiErrorCode.USER_NOTEXIST,
      ); // 抛出错误，以便客户端进行处理
    }
  }
}
